﻿namespace com.net.wifi_pvp
{
    using com.game;
    using com.game.basic;
    using com.game.basic.events;
    using com.game.consts;
    using com.game.data;
    using com.game.manager;
    using com.game.module.core;
    using com.game.module.effect;
    using com.game.module.General;
    using com.game.module.WiFiPvP;
    using com.game.Public.Confirm;
    using com.game.Public.Message;
    using com.game.vo;
    using com.net;
    using com.u3d.bases.display.controler;
    using PCustomDataType;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using TNet;
    using UnityEngine;

    internal class WifiLAN
    {
        private bool _isInEnding;
        private WifiPvpConst.PVPEndState _lastEndFlag;
        private string _lastUniqRequestString;
        [CompilerGenerated]
        private static Dictionary<string, int> <>f__switch$map36;
        private Dictionary<IPEndPoint, ServerList.Entry> cacheDic = new Dictionary<IPEndPoint, ServerList.Entry>();
        private int cnt;
        private string deviceString;
        private WifiPvpConst.PVPEndState endFlag = WifiPvpConst.PVPEndState.ended;
        private SGameClient gc;
        private SGameServer gs;
        private int idx;
        public static readonly WifiLAN Instance;
        private bool isConnected;
        private bool isInConfirmingMutex;
        private bool isInitialized;
        private bool isInPvp;
        private bool isMaster;
        private bool isMeLoadingFinished;
        private string lastHostName;
        private SPVPLobbyClient lc;
        private int loadFinishedCounter;
        private SPVPLobbyServer ls;
        private int lsListenPort;
        private IEnumerable<System.Action> mainThreadCallbackList = new System.Collections.Generic.List<System.Action>();
        private MeControler meController;
        private PVPFighter myFullInfo = new PVPFighter();
        private string myHostName;
        private string myIP = Network.player.ipAddress;
        private TcpPlayer player;
        public System.Collections.Generic.List<RpcData> rpcList = new System.Collections.Generic.List<RpcData>();
        private vp_Timer.Handle timeHandle = new vp_Timer.Handle();

        static WifiLAN()
        {
            if (Instance == null)
            {
            }
            Instance = new WifiLAN();
        }

        public void AddNewPeerToIpList(PIntranetPlayer player)
        {
            if (this.lc != null)
            {
                this.lc.AddIpToRemoteList(player.playerIp);
            }
        }

        private void AttrsChangeListener(int type, int v1, int v2, object data)
        {
            this.DoUpdateMyFighterInfo();
        }

        private void ClearAfterConnectionClosed()
        {
            this.player = null;
            this.isInPvp = false;
            this.isConnected = false;
            this.loadFinishedCounter = 0;
            this.EndFlag = WifiPvpConst.PVPEndState.ended;
            this.isInConfirmingMutex = false;
            this.isMeLoadingFinished = false;
            this.IsInEnding = false;
        }

        private void ClientOnConnect(bool success, string message)
        {
            Debug.Log("作为SGameClient, 开始连接SGameServer! 连接结果:" + success.ToString());
            if (success)
            {
                vp_Timer.In(0.5f, delegate {
                    BinaryWriter bw = this.gc.BeginSend();
                    string extraMessage = this.myHostName;
                    RpcData data = new RpcData(WifiPvpConst.MsgType.C_CONNECTION_OK, null, extraMessage);
                    bw.WriteObject(data);
                    this.gc.EndSend();
                    this.isConnected = true;
                }, null);
            }
            else
            {
                this.GiveUp();
                MessageManager.Show("对方已掉线");
            }
        }

        private void ClientOnDisconnect()
        {
            this.isConnected = false;
            this.DoClientOnDisconnect();
        }

        private void ClientOnPacket(Packet response, BinaryReader reader, IPEndPoint source)
        {
            RpcData item = reader.ReadObject() as RpcData;
            System.Collections.Generic.List<RpcData> rpcList = this.rpcList;
            lock (rpcList)
            {
                this.rpcList.Add(item);
            }
        }

        private void ConfirmPVPAndConnect(InviteData inviteData)
        {
            if (inviteData == null)
            {
                Debug.Log("错误, 当前并无邀请");
            }
            else
            {
                this.isInPvp = true;
                this.isMaster = false;
                this.ls.UserResponseJoin(inviteData.ipEnt.externalAddress, true);
                this.gc = this.StartSGameClient(inviteData.ipEnt.externalAddress, inviteData.ipEnt.internalAddress);
                Singleton<WifiPvpMode>.Instance.enemyFighterInfo = ParseHostString(inviteData.ipEnt.name);
                Singleton<WifiPvpMode>.Instance.myFighterInfo = ParseHostString(this.myHostName);
            }
            this.isInConfirmingMutex = false;
        }

        private void DenyPVPRequest(InviteData data)
        {
            if (data == null)
            {
                Debug.Log("错误, 当前并无邀请");
            }
            else
            {
                this.ls.UserResponseJoin(data.ipEnt.externalAddress, false);
            }
            this.isInConfirmingMutex = false;
        }

        public static void Destroy()
        {
            Instance.DestroyAll();
        }

        private void DestroyAll()
        {
            if (this.isInitialized)
            {
                this.UnregisterListeners();
                this.EndLobbyClient();
                this.EndLobbyServer();
                this.EndSGameClient();
                this.EndSGameServer();
                this.isInitialized = false;
                GC();
            }
        }

        private void DoClientOnDisconnect()
        {
            if (this.EndFlag == WifiPvpConst.PVPEndState.confirming)
            {
                Debug.Log("互相确认对战的过程中断线, 放弃本次对战");
                this.GiveUp();
            }
            else if ((this.EndFlag != WifiPvpConst.PVPEndState.ended) && (this.EndFlag != WifiPvpConst.PVPEndState.abort))
            {
                Debug.Log("GameClient found disconnected, quiting pvp...");
                this.QuitPVP(false);
            }
            else
            {
                Debug.Log("客户端断开连接. 但当前状态已经是ended");
            }
        }

        private void DoEndAsGameClient()
        {
            try
            {
                this.EndSGameClient();
            }
            catch (Exception exception)
            {
                Debug.LogWarning("作为SGameClient退出WiFi PVP报错: 报错内容" + exception.Message);
            }
        }

        private void DoEndAsGameServer()
        {
            try
            {
                this.EndLobbyClient();
                this.EndSGameServer();
            }
            catch (Exception exception)
            {
                Debug.LogWarning("作为SGameServer退出WiFi PVP报错, 报错内容: " + exception.Message);
            }
        }

        private void DoGiveupAsGameClient()
        {
            try
            {
                this.EndSGameClient();
            }
            catch (Exception exception)
            {
                Debug.LogWarning("作为SGameClient退出Wifi PVP报错, 内容:" + exception.ToString());
            }
        }

        private void DoGiveupAsGameServer()
        {
            try
            {
                this.EndSGameServer();
            }
            catch (Exception exception)
            {
                Debug.LogWarning("作为SGameServer退出Wifi PVP报错, 内容:" + exception.ToString());
            }
        }

        private static void DoParseAccountInfoFromHostString(string p, PVPFighter fighter)
        {
            char[] separator = new char[] { '#' };
            string[] strArray = p.Split(separator);
            fighter.acc.accountName = strArray[0];
            fighter.acc.accountLevel = strArray[1];
            fighter.acc.isAvailable = Convert.ToBoolean(byte.Parse(strArray[2]));
            fighter.acc.onFightGeneralId = strArray[3];
            fighter.acc.accountFightEffect = strArray[4];
        }

        private static void DoParseGeneralBriefFromHostString(string[] stringList, PVPFighter fighter)
        {
            foreach (string str in stringList)
            {
                if (str == string.Empty)
                {
                    break;
                }
                char[] separator = new char[] { '#' };
                string[] strArray2 = str.Split(separator);
                PVPGeneralBrief item = new PVPGeneralBrief {
                    id = strArray2[0],
                    generalTid = strArray2[1],
                    level = strArray2[2],
                    starInfo = strArray2[3],
                    job = strArray2[4],
                    name = strArray2[5]
                };
                fighter.genList.Add(item);
            }
        }

        private void DoSend(RpcData rpcObj)
        {
            if (rpcObj != null)
            {
                try
                {
                    if (this.isMaster)
                    {
                        TNet.Buffer buf = TNet.Buffer.Create();
                        buf.BeginPacket().WriteObject(rpcObj);
                        buf.EndPacket();
                        this.player.SendTcpPacket(buf);
                        buf.Recycle();
                        buf = null;
                    }
                    else
                    {
                        this.gc.BeginSend().WriteObject(rpcObj);
                        this.gc.EndSend();
                    }
                }
                catch (Exception exception)
                {
                    Debug.LogWarning("DoSend报错:" + exception.Message);
                }
            }
        }

        private void DoSendToSelf(RpcData rpcObj)
        {
            if (rpcObj != null)
            {
                AppNet.main.receiveNetMsg(new NetData(rpcObj.buffer));
            }
        }

        private void DoServerOnDisconnect()
        {
            if (this.EndFlag == WifiPvpConst.PVPEndState.confirming)
            {
                Debug.Log("互相确认对战的过程中断线, 放弃本次对战");
                this.GiveUp();
            }
            else if ((this.EndFlag != WifiPvpConst.PVPEndState.ended) && (this.EndFlag != WifiPvpConst.PVPEndState.abort))
            {
                Debug.Log("game server found disconnected: quitting pvp...");
                this.QuitPVP(false);
            }
            else
            {
                Debug.Log("主机端断开连接, 但状态已经ended");
            }
        }

        private void DoStartSPVPLobbyClient(TNet.List<string> ipList = null)
        {
            SPVPLobbyClient client = new SPVPLobbyClient(0x23b2, 0x23b9, this.myIP, this.lsListenPort, ipList, 0x9c4L) {
                onResponseJoin = new SPVPLobbyClient.OnResponseJoin(this.LobbyClientOnResponseJoin)
            };
            this.lc = client;
        }

        private void DoUpdateMyFighterInfo()
        {
            this.myFullInfo.acc.accountName = MeVo.instance.Name;
            this.myFullInfo.acc.accountLevel = MeVo.instance.Level.ToString();
            this.myFullInfo.acc.onFightGeneralId = MeVo.instance.generalTemplateInfo.general_id.ToString();
            this.myFullInfo.acc.accountFightEffect = MeVo.instance.fightPoint.ToString();
            this.myFullInfo.genList.Clear();
            foreach (GeneralInfo info in Singleton<GeneralMode>.Instance.generalInfoList.Values)
            {
                if (info.place > 0)
                {
                    PVPGeneralBrief item = new PVPGeneralBrief {
                        id = info.id.ToString(),
                        generalTid = info.genralTemplateInfo.general_id.ToString(),
                        name = info.genralTemplateInfo.name,
                        job = info.genralTemplateInfo.career.ToString(),
                        starInfo = UnityEngine.Random.Range(1, 5).ToString(),
                        level = info.lvl.ToString()
                    };
                    this.myFullInfo.genList.Add(item);
                }
            }
        }

        private void EndLobbyClient()
        {
            if (this.lc != null)
            {
                this.lc.Stop();
                this.lc = null;
            }
            GC();
        }

        private void EndLobbyServer()
        {
            this.ls.Stop();
            this.ls = null;
        }

        private void EndSGameClient()
        {
            if ((this.gc != null) && this.gc.isConnected)
            {
                this.gc.Disconnect();
            }
            this.gc = null;
            GC();
        }

        private void EndSGameServer()
        {
            if (this.gs != null)
            {
                this.gs.Stop();
                this.gs = null;
            }
            GC();
        }

        public void EnterPVPFinal()
        {
            if (this.isInPvp && this.isMaster)
            {
                if (this.isConnected)
                {
                    Debug.Log("S -> C: EnterPVPStepFinal");
                    Singleton<WifiPvpView>.Instance.CloseView();
                    Singleton<WifiPvpMode>.Instance.EnterPVPScence(true, 1);
                    this.Send(new RpcData(WifiPvpConst.MsgType.S_ACK_ENTER, null, null));
                }
                else
                {
                    MessageManager.Show(LanguageManager.GetWord("WifiPvp.EnemyOffline"));
                    this.GiveUp();
                }
            }
        }

        public void EnterPVPStepOne(RpcData data)
        {
            if (this.isInPvp && this.isMaster)
            {
                Debug.Log("主机打开确认面板 并发送基本信息给从机端");
                this.isConnected = true;
                this.loadFinishedCounter = 0;
                this.isMeLoadingFinished = false;
                this.EndFlag = WifiPvpConst.PVPEndState.confirming;
                Singleton<WifiPvpMode>.Instance.myFighterInfo = ParseHostString(this.myHostName);
                Singleton<WifiPvpMode>.Instance.enemyFighterInfo = ParseHostString(data.extraMessage);
                Singleton<WifiPvpMode>.Instance.currentMode = WifiPvpMode.ViewMode.confrom;
                Singleton<WifiPvpView>.Instance.OpenView();
                string myHostName = this.myHostName;
                this.Send(new RpcData(WifiPvpConst.MsgType.S_TO_C_BASIC_INFO, null, myHostName));
                ConfirmMgr.Instance.CancelTimerTipAlert();
                this.isInConfirmingMutex = false;
                this.InitMasterConfirmView();
            }
        }

        public void EnterPVPStepThree()
        {
            this.UpdateMasterConfirmView();
        }

        public void EnterPVPStepTwo(RpcData data)
        {
            if (this.isInPvp && !this.isMaster)
            {
                if (this.isConnected)
                {
                    Debug.Log("从机端打开确认面板");
                    this.loadFinishedCounter = 0;
                    this.isMeLoadingFinished = false;
                    this.EndFlag = WifiPvpConst.PVPEndState.confirming;
                    Singleton<WifiPvpMode>.Instance.myFighterInfo = ParseHostString(this.myHostName);
                    Singleton<WifiPvpMode>.Instance.enemyFighterInfo = ParseHostString(data.extraMessage);
                    Singleton<WifiPvpMode>.Instance.currentMode = WifiPvpMode.ViewMode.confrom;
                    Singleton<WifiPvpView>.Instance.OpenView();
                    this.InitClientConfirmView();
                }
                else
                {
                    this.GiveUp();
                }
            }
        }

        private static void GC()
        {
            System.GC.Collect();
        }

        private static string GenerateInviteRequestFromHostName(string p)
        {
            PVPAccountBrief accountBriefFromHostString = GetAccountBriefFromHostString(p);
            return LanguageManager.GetWord("WifiPvp.SendInvitation", accountBriefFromHostString.accountName);
        }

        public static PVPAccountBrief GetAccountBriefFromHostString(string s)
        {
            PVPFighter fighter = new PVPFighter();
            char[] separator = new char[] { '*' };
            DoParseAccountInfoFromHostString(s.Split(separator)[0], fighter);
            return fighter.acc;
        }

        public static string GetNameFromIp(LobbyServerItem item)
        {
            string str = string.Empty;
            IPEndPoint iPEP = item.IPEP;
            int port = iPEP.Port;
            string key = iPEP.Address.ToString();
            if (key != null)
            {
                int num2;
                if (<>f__switch$map36 == null)
                {
                    Dictionary<string, int> dictionary = new Dictionary<string, int>(0x18);
                    dictionary.Add("172.16.243.149", 0);
                    dictionary.Add("172.16.243.54", 1);
                    dictionary.Add("172.16.243.145", 2);
                    dictionary.Add("172.16.243.128", 3);
                    dictionary.Add("172.16.243.119", 4);
                    dictionary.Add("172.16.241.112", 5);
                    dictionary.Add("172.16.243.138", 6);
                    dictionary.Add("172.16.243.151", 7);
                    dictionary.Add("172.16.243.137", 8);
                    dictionary.Add("172.16.243.136", 9);
                    dictionary.Add("172.16.243.155", 10);
                    dictionary.Add("172.16.243.85", 11);
                    dictionary.Add("172.16.243.140", 12);
                    dictionary.Add("172.16.243.142", 13);
                    dictionary.Add("172.16.243.125", 14);
                    dictionary.Add("172.16.243.127", 15);
                    dictionary.Add("172.16.143.133", 0x10);
                    dictionary.Add("172.16.241.93", 0x11);
                    dictionary.Add("172.16.243.146", 0x12);
                    dictionary.Add("172.16.243.110", 0x13);
                    dictionary.Add("172.16.243.101", 20);
                    dictionary.Add("172.16.243.181", 0x15);
                    dictionary.Add("172.16.243.178", 0x16);
                    dictionary.Add("172.16.243.148", 0x17);
                    <>f__switch$map36 = dictionary;
                }
                if (<>f__switch$map36.TryGetValue(key, out num2))
                {
                    switch (num2)
                    {
                        case 0:
                            str = "王雄";
                            break;

                        case 1:
                            str = "烧饼";
                            break;

                        case 2:
                            str = "雪芬";
                            break;

                        case 3:
                            str = "菜园";
                            break;

                        case 4:
                            str = "Uncle娟";
                            break;

                        case 5:
                            str = "宗儒";
                            break;

                        case 6:
                            str = "浪爷";
                            break;

                        case 7:
                            str = "阿牛";
                            break;

                        case 8:
                            str = "永安";
                            break;

                        case 9:
                            str = "清清";
                            break;

                        case 10:
                            str = "有玮";
                            break;

                        case 11:
                            str = "涛哥";
                            break;

                        case 12:
                            str = "小雄";
                            break;

                        case 13:
                            str = "阿真";
                            break;

                        case 14:
                            str = "宗姚";
                            break;

                        case 15:
                            str = "鹏飞";
                            break;

                        case 0x10:
                            str = "朋朋";
                            break;

                        case 0x11:
                            str = "黄源";
                            break;

                        case 0x12:
                            str = "森爷";
                            break;

                        case 0x13:
                            str = "教授";
                            break;

                        case 20:
                            str = "朝阳";
                            break;

                        case 0x15:
                            str = "俊文哥";
                            break;

                        case 0x16:
                            str = "周源";
                            break;

                        case 0x17:
                            str = "李勇";
                            break;
                    }
                }
            }
            return (!(str == string.Empty) ? (str + port) : item.accountName);
        }

        private WifiPvpConst.PVPEndState GetOppositeEndFlag(WifiPvpConst.PVPEndState state)
        {
            if (state == WifiPvpConst.PVPEndState.win)
            {
                return WifiPvpConst.PVPEndState.fail;
            }
            if (state == WifiPvpConst.PVPEndState.fail)
            {
                return WifiPvpConst.PVPEndState.win;
            }
            return WifiPvpConst.PVPEndState.abort;
        }

        public string GetUniqInviteId()
        {
            if (this.deviceString == null)
            {
            }
            this.deviceString = SystemInfo.deviceUniqueIdentifier;
            string str = (((long) Time.time) % 10L).ToString();
            return (this.deviceString + str + '@');
        }

        private void GiveUp()
        {
            Debug.Log("Give up!");
            WifiPvpManager.Instance.DisableAllAi();
            Singleton<WifiPvpMode>.Instance.currentMode = WifiPvpMode.ViewMode.selecet;
            Singleton<WifiPvpView>.Instance.OpenView();
            if (this.isMaster)
            {
                vp_Timer.In(0.1f, new vp_Timer.Callback(this.DoGiveupAsGameServer), null);
            }
            else
            {
                vp_Timer.In(0.1f, new vp_Timer.Callback(this.DoGiveupAsGameClient), null);
            }
            this.player = null;
            this.isInPvp = false;
            this.loadFinishedCounter = 0;
            this.EndFlag = WifiPvpConst.PVPEndState.ended;
            this.isMeLoadingFinished = false;
            this.isInConfirmingMutex = false;
            WifiPvpManager.Instance.HandleCloseEndView();
        }

        private void HandleInvitationReply(bool accept)
        {
            Debug.Log("收到邀请");
            this.isInPvp = accept;
            this.isMaster = accept;
            if (!accept)
            {
                MessageManager.Show(LanguageManager.GetWord("WifiPvp.EnemyRefused"));
                ConfirmMgr.Instance.CancelTimerTipAlert();
            }
            this.isInConfirmingMutex = false;
        }

        public void HandlePressChangeButton()
        {
            this.TellOtherGivingUp();
            this.GiveUp();
        }

        private void HandleReceivedEndMsg(RpcData data)
        {
            char[] separator = new char[] { '#' };
            string[] strArray = data.extraMessage.Split(separator);
            byte num = byte.Parse(strArray[0]);
            bool rightNow = bool.Parse(strArray[1]);
            WifiPvpConst.PVPEndState state = (WifiPvpConst.PVPEndState) num;
            this.EndFlag = this.GetOppositeEndFlag(state);
            Debug.Log("收到对方通知结束的消息: endFlag:" + this.EndFlag);
            this.QuitPVP(rightNow);
        }

        private void HandleReceivedGiveUpMsg(RpcData data)
        {
            this.GiveUp();
            MessageManager.Show(LanguageManager.GetWord("WifiPvp.EnemyGaveup"));
        }

        private void HandleReceivedRPCData(RpcData data)
        {
            if (!this.isInPvp && !this.IsInEnding)
            {
                this.QuitPVP(true);
            }
            else
            {
                switch (data.msg_type)
                {
                    case WifiPvpConst.MsgType.C_CONNECTION_OK:
                        this.EnterPVPStepOne(data);
                        break;

                    case WifiPvpConst.MsgType.S_TO_C_BASIC_INFO:
                        this.EnterPVPStepTwo(data);
                        break;

                    case WifiPvpConst.MsgType.C_REQUEST_ENTER:
                        this.EnterPVPStepThree();
                        break;

                    case WifiPvpConst.MsgType.S_ACK_ENTER:
                        Singleton<WifiPvpView>.Instance.CloseView();
                        Singleton<WifiPvpMode>.Instance.EnterPVPScence(false, 1);
                        break;

                    case WifiPvpConst.MsgType.C_LOADING_OK:
                        this.SGameClientLoadingFinish();
                        break;

                    case WifiPvpConst.MsgType.S_LOADING_OK:
                        this.SGameClientSyncPropertyToServer();
                        break;

                    case WifiPvpConst.MsgType.INFORM_END_PVP:
                        this.HandleReceivedEndMsg(data);
                        break;

                    case WifiPvpConst.MsgType.GIVE_UP:
                        this.HandleReceivedGiveUpMsg(data);
                        break;

                    case WifiPvpConst.MsgType.PROTOCAL:
                        AppNet.main.receiveNetMsg(new NetData(data.buffer));
                        break;
                }
            }
        }

        private void InitClientConfirmView()
        {
            if (Singleton<WifiPvpConfromView>.Instance.IsOpened)
            {
                string label = LanguageManager.GetWord("WifiPvp.ConfirmViewEnter");
                UIWidgetContainer.VoidDelegate callback = delegate (GameObject go) {
                    string word = LanguageManager.GetWord("WifiPvp.ConfirmViewWaitForEnemy");
                    Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.StartButton, true, false, word, null);
                    Debug.Log("客户端按下Start按钮");
                    this.Send(new RpcData(WifiPvpConst.MsgType.C_REQUEST_ENTER, null, null));
                };
                Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.StartButton, true, true, label, callback);
            }
            else
            {
                vp_Timer.In(0.2f, new vp_Timer.Callback(this.InitClientConfirmView), null);
            }
        }

        public void InitMasterConfirmView()
        {
            if (Singleton<WifiPvpConfromView>.Instance.IsOpened)
            {
                string word = LanguageManager.GetWord("WifiPvp.ConfirmViewWaitForEnemy");
                Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.StartButton, true, false, word, null);
                word = LanguageManager.GetWord("WifiPvp.ConfirmChange");
                Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.ChangeButton, false, false, word, null);
            }
            else
            {
                vp_Timer.In(0.2f, new vp_Timer.Callback(this.InitMasterConfirmView), null);
            }
        }

        private void LobbyClientOnResponseJoin(IPEndPoint inviteIp, bool accept)
        {
            this.HandleInvitationReply(accept);
        }

        private void LobbyClientUpdate()
        {
            if ((this.lc != null) && !this.isInPvp)
            {
                this.lc.Update();
                Singleton<WifiPvpMode>.Instance.SetLobbyServerList(this.lc.knownServers.list);
            }
        }

        private void LobbyServerUpdate()
        {
            if ((this.ls != null) && !this.isInPvp)
            {
                InviteData[] dataArray = this.ls.PullInviteGSList();
                if (dataArray != null)
                {
                    foreach (InviteData data in dataArray)
                    {
                        try
                        {
                            char[] separator = new char[] { '@' };
                            if (data.key.Split(separator)[0] != this._lastUniqRequestString)
                            {
                                this.PropmtForConfirm(data);
                                break;
                            }
                        }
                        catch (Exception exception)
                        {
                            Debug.LogWarning("解析InviteData[] 报错" + exception.ToString());
                        }
                    }
                }
            }
            this.UpdateMyHostNameFromFighterInfo();
        }

        private void MainUpdate()
        {
            IEnumerator<System.Action> enumerator = this.mainThreadCallbackList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    System.Action current = enumerator.Current;
                    current();
                }
            }
            finally
            {
                if (enumerator == null)
                {
                }
                enumerator.Dispose();
            }
            this.cnt = Mathf.Min(this.rpcList.Count, 30);
            if (this.cnt != 0)
            {
                System.Collections.Generic.List<RpcData> rpcList = this.rpcList;
                lock (rpcList)
                {
                    this.idx = 0;
                    while (this.idx < this.cnt)
                    {
                        this.HandleReceivedRPCData(this.rpcList[this.idx]);
                        this.idx++;
                    }
                    this.rpcList.RemoveRange(0, this.cnt);
                }
            }
        }

        private static PVPFighter ParseHostString(string s)
        {
            PVPFighter fighter = new PVPFighter();
            char[] separator = new char[] { '*' };
            string[] strArray = s.Split(separator);
            DoParseAccountInfoFromHostString(strArray[0], fighter);
            char[] chArray2 = new char[] { '$' };
            DoParseGeneralBriefFromHostString(strArray[1].Split(chArray2), fighter);
            return fighter;
        }

        private TNet.List<string> ParseToTNetList(System.Collections.Generic.List<PIntranetPlayer> list)
        {
            TNet.List<string> list2 = new TNet.List<string>();
            foreach (PIntranetPlayer player in list)
            {
                list2.Add(player.playerIp);
            }
            return list2;
        }

        private void PropmtForConfirm(InviteData data)
        {
            <PropmtForConfirm>c__AnonStorey103 storey = new <PropmtForConfirm>c__AnonStorey103 {
                data = data,
                <>f__this = this
            };
            char[] separator = new char[] { '@' };
            string[] strArray = storey.data.key.Split(separator);
            this._lastUniqRequestString = strArray[0];
            if (!AppMap.Instance.IsInWifiPVP && !GlobalData.isInCopy)
            {
                if (!this.isInConfirmingMutex)
                {
                    this.isInConfirmingMutex = true;
                    ConfirmMgr.Instance.CancelTimerTipAlert();
                    ConfirmMgr.Instance.ShowTimeOkCancelAlert(GenerateInviteRequestFromHostName(strArray[1]), 10, "OK_CANCEL", new ClickCallback(storey.<>m__10E), new ClickCallback(storey.<>m__10F));
                }
                else
                {
                    this.isInConfirmingMutex = true;
                    this.DenyPVPRequest(storey.data);
                    this.isInConfirmingMutex = true;
                }
            }
            else
            {
                this.isInConfirmingMutex = true;
                this.DenyPVPRequest(storey.data);
            }
        }

        public void PVPEndAndTellOther(WifiPvpConst.PVPEndState state, bool rightNow)
        {
            if (state == WifiPvpConst.PVPEndState.started)
            {
                state = WifiPvpConst.PVPEndState.abort;
                Debug.Log("改为aborted 1");
            }
            Debug.Log("我方通知PVP结束, 结果:" + state.ToString());
            this.EndFlag = state;
            this.TellOtherToEndPVP(this.EndFlag, rightNow);
            this.QuitPVP(rightNow);
        }

        public void PVPLoadingFinish()
        {
            if (!this.isMeLoadingFinished && this.isInitialized)
            {
                this.isMeLoadingFinished = true;
                if (!this.isMaster)
                {
                    this.TellSGameServerLoadingFinish();
                }
                this.loadFinishedCounter++;
            }
        }

        private void QuitPVP(WifiPvpConst.PVPEndState status)
        {
            if (status == WifiPvpConst.PVPEndState.started)
            {
                this.EndFlag = WifiPvpConst.PVPEndState.abort;
            }
            WifiPvpManager.Instance.DisableAllAi();
            this.ShowEndView();
            if (this.isMaster)
            {
                vp_Timer.In(2f, delegate {
                    this.DoEndAsGameServer();
                    this.ClearAfterConnectionClosed();
                }, null);
            }
            else
            {
                vp_Timer.In(2f, delegate {
                    this.DoEndAsGameClient();
                    this.ClearAfterConnectionClosed();
                }, null);
            }
        }

        private void QuitPVP(bool rightNow = false)
        {
            WifiPvpManager.Instance.DisableAllAi();
            Debug.Log("进入QuitPVP流程,isRightNow:" + rightNow);
            if (!this.IsInEnding)
            {
                this.IsInEnding = true;
                if (rightNow)
                {
                    this.QuitPVP(this.EndFlag);
                }
                else
                {
                    vp_Timer.In(2.5f, () => this.QuitPVP(this.EndFlag), null);
                }
            }
        }

        private void RegisterListeners()
        {
            GlobalAPI.facade.Add(300, new NoticeListener(this.AttrsChangeListener));
            GlobalAPI.facade.Add(0x12d, new NoticeListener(this.AttrsChangeListener));
        }

        public void RemovePeerFromIpList(PIntranetPlayer player)
        {
            if (this.lc != null)
            {
                this.lc.RemoveIpFromRemoteList(player.playerIp);
            }
        }

        [Obsolete]
        private void RemovePVPEffect()
        {
            foreach (string str in EffectId.PVPEffects)
            {
                EffectMgr.Instance.RemoveSceneEffect(str);
            }
        }

        public void Send(RpcData data)
        {
            this.DoSend(data);
        }

        public void Send(MemoryStream msdata, byte framNum, byte wayNum)
        {
            this.Send(RpcData.GetRpcProtocol(msdata, framNum, wayNum));
        }

        private void SendAttrsAndPosToOther(WifiPvpConst.Sender sender)
        {
            Singleton<WifiPvpMode>.Instance.TellMyHeroTowerAndBaseToOther(sender);
        }

        public void SendInvitation(IPEndPoint targetIPEP)
        {
            if (!this.isInConfirmingMutex)
            {
                Debug.Log("发送邀请");
                this.UpdateSavedDic(this.lc.knownServers.list);
                if (!this.cacheDic.ContainsKey(targetIPEP))
                {
                    MessageManager.Show(LanguageManager.GetWord("WifiPvp.CantChallenge"));
                }
                else
                {
                    this.lc.InviteIPJoin(targetIPEP, this.gs.name, new IPEndPoint(this.ls.curInternalIP, this.gs.tcpPort), 0, this.GetUniqInviteId() + this.myHostName);
                    Singleton<WifiPvpMode>.Instance.enemyFighterInfo = ParseHostString(this.cacheDic[targetIPEP].name);
                    Singleton<WifiPvpMode>.Instance.myFighterInfo = ParseHostString(this.myHostName);
                    ConfirmMgr.Instance.ShowTimeTips(WifiPvpConst.WAIT_PROMPT, 9, (ClickCallback) (() => (this.isInConfirmingMutex = false)));
                    this.isInConfirmingMutex = true;
                }
            }
        }

        public void SendToSelf(RpcData data)
        {
            this.DoSendToSelf(data);
        }

        public void SendToSelf(MemoryStream msdata, byte framNum, byte wayNum)
        {
            this.SendToSelf(RpcData.GetRpcProtocol(msdata, framNum, wayNum));
        }

        private void ServerOnConnect(Player p)
        {
            this.isConnected = true;
        }

        private void ServerOnCustomPacket(TcpPlayer tcpPlayer, TNet.Buffer buffer, BinaryReader reader, Packet request, bool reliable)
        {
            if (this.player == null)
            {
            }
            this.player = tcpPlayer;
            RpcData item = reader.ReadObject() as RpcData;
            System.Collections.Generic.List<RpcData> rpcList = this.rpcList;
            lock (rpcList)
            {
                this.rpcList.Add(item);
            }
        }

        private void ServerOnDisconnect(Player p)
        {
            this.isConnected = false;
            this.DoServerOnDisconnect();
        }

        public void SGameClientLoadingFinish()
        {
            if (this.loadFinishedCounter == 2)
            {
                vp_Timer.CancelAll("SGameClientLoadingFinish");
            }
            else if (this.isMaster)
            {
                if (this.isMeLoadingFinished)
                {
                    this.SGameServerSyncPropertyToClient();
                }
                else
                {
                    vp_Timer.In(0.1f, new vp_Timer.Callback(this.SGameClientLoadingFinish), null);
                }
            }
        }

        public void SGameClientSyncPropertyToServer()
        {
            if (!this.isMaster)
            {
                this.SendAttrsAndPosToOther(WifiPvpConst.Sender.SGAME_CLIENT);
            }
            else
            {
                Debug.LogWarning("尝试作为SGameClient同步属性, 但并非从机");
            }
        }

        private void SGameClientUpdate()
        {
            if ((this.gc != null) && this.isInitialized)
            {
                this.gc.ProcessPackets();
            }
        }

        public void SGameServerSyncPropertyToClient()
        {
            if (this.isMaster)
            {
                this.Send(new RpcData(WifiPvpConst.MsgType.S_LOADING_OK, null, null));
                this.SendAttrsAndPosToOther(WifiPvpConst.Sender.SGAME_SERVER);
            }
            else
            {
                Debug.LogWarning("尝试作为SGameServer同步属性, 但并非主机");
            }
        }

        private void SGameServerUpdate()
        {
            if ((this.gs != null) && this.isInitialized)
            {
                this.gs.Update();
            }
        }

        private void ShowEndView()
        {
            WifiPvpConst.PVPEndState state = (this.EndFlag != WifiPvpConst.PVPEndState.abort) ? this.EndFlag : WifiPvpConst.PVPEndState.win;
            Singleton<WifiPvpMode>.Instance.currentMode = WifiPvpMode.ViewMode.win;
            Singleton<WifiPvpMode>.Instance.result = state;
            Singleton<WifiPvpView>.Instance.OpenView();
        }

        public void Start()
        {
            if (!this.isInitialized)
            {
                this.UpdateMyHostName();
                this.StartLobbyServer();
                this.RegisterListeners();
                this.isInitialized = true;
            }
        }

        public void StartFindPeer()
        {
            if (this.isInitialized)
            {
                if (this.isInPvp)
                {
                    Debug.Log("已在PVP, 停止gs和ls");
                    this.QuitPVP(false);
                }
                this.StartLobbyClient();
            }
        }

        public void StartFindPeer(System.Collections.Generic.List<PIntranetPlayer> list)
        {
            if (this.isInitialized)
            {
                if (this.isInPvp)
                {
                    Debug.Log("已在PVP, 停止gs和ls");
                    this.QuitPVP(false);
                }
                TNet.List<string> ipList = this.ParseToTNetList(list);
                this.StartLobbyClient(ipList);
            }
        }

        private void StartLobbyClient()
        {
            if ((this.ls == null) && this.isInitialized)
            {
                this.StartLobbyServer();
            }
            if ((this.gs == null) && this.isInitialized)
            {
                this.StartSGameServer();
            }
            if ((this.lc == null) && this.isInitialized)
            {
                this.DoStartSPVPLobbyClient(null);
            }
            this.lc.Start();
        }

        private void StartLobbyClient(TNet.List<string> ipList)
        {
            if ((this.ls == null) && this.isInitialized)
            {
                this.StartLobbyServer();
            }
            if ((this.gs == null) && this.isInitialized)
            {
                this.StartSGameServer();
            }
            if ((this.lc == null) && this.isInitialized)
            {
                this.DoStartSPVPLobbyClient(ipList);
            }
            this.lc.Start();
        }

        private void StartLobbyServer()
        {
            if (this.ls == null)
            {
                this.ls = new SPVPLobbyServer();
            }
            this.ls.UpdateIpEnt(this.myHostName, 0);
            this.lsListenPort = UnityEngine.Random.Range(0x23b2, 0x23b9);
            try
            {
                if (!this.ls.Start(this.lsListenPort))
                {
                    this.lsListenPort = UnityEngine.Random.Range(0x23b2, 0x23b9);
                    this.ls.Start(this.lsListenPort);
                }
            }
            catch (Exception exception)
            {
                Debug.LogWarning("启动LobbyServer报错: " + exception.Message);
            }
        }

        private SGameClient StartSGameClient(IPEndPoint externalIPEP, IPEndPoint internalIPEP)
        {
            if ((this.gc != null) && this.gc.isConnected)
            {
                this.EndSGameClient();
            }
            if (this.gc == null)
            {
                SGameClient client = new SGameClient {
                    onConnect = new SGameClient.OnConnect(this.ClientOnConnect),
                    onDisconnect = new SGameClient.OnDisconnect(this.ClientOnDisconnect)
                };
                this.gc = client;
                this.gc.packetHandlers.Add(new SGameClient.OnPacket(this.ClientOnPacket));
            }
            this.gc.Connect(externalIPEP, internalIPEP);
            return this.gc;
        }

        private void StartSGameServer()
        {
            if ((this.gs == null) && this.isInitialized)
            {
                SGameServer server = new SGameServer {
                    name = this.myHostName,
                    onPlayerConnect = new SGameServer.OnPlayerAction(this.ServerOnConnect),
                    onCustomPacket = new SGameServer.OnCustomPacket(this.ServerOnCustomPacket),
                    onPlayerDisconnect = new SGameServer.OnPlayerAction(this.ServerOnDisconnect)
                };
                this.gs = server;
            }
            int tcpPort = UnityEngine.Random.Range(0x4e20, 0xea60);
            try
            {
                if (!this.gs.Start(tcpPort))
                {
                    tcpPort = UnityEngine.Random.Range(0x4e20, 0xea60);
                    this.gs.Start(tcpPort);
                }
            }
            catch (Exception exception)
            {
                Debug.LogWarning("启动SGameServer报错: " + exception.Message);
            }
        }

        public void StopFindingPeer()
        {
            if (this.lc != null)
            {
                this.lc.Stop();
                this.lc = null;
            }
            if (!this.isInPvp && (this.gs != null))
            {
                this.gs.Stop();
                this.gs = null;
            }
        }

        private void TellOtherGivingUp()
        {
            RpcData data = new RpcData(WifiPvpConst.MsgType.GIVE_UP, null, null);
            this.Send(data);
        }

        private void TellOtherToEndPVP(WifiPvpConst.PVPEndState state, bool endRightNow)
        {
            string extraMessage = ((byte) state).ToString() + '#' + endRightNow.ToString();
            RpcData data = new RpcData(WifiPvpConst.MsgType.INFORM_END_PVP, null, extraMessage);
            this.Send(data);
        }

        public void TellSGameServerLoadingFinish()
        {
            this.Send(new RpcData(WifiPvpConst.MsgType.C_LOADING_OK, null, null));
        }

        private void UnregisterListeners()
        {
            GlobalAPI.facade.Remove(300, new NoticeListener(this.AttrsChangeListener));
            GlobalAPI.facade.Remove(0x12d, new NoticeListener(this.AttrsChangeListener));
        }

        public void Update()
        {
            if (this.isInitialized)
            {
                this.SGameServerUpdate();
                this.LobbyServerUpdate();
                this.LobbyClientUpdate();
                this.SGameClientUpdate();
                this.MainUpdate();
            }
        }

        private void UpdateMasterConfirmView()
        {
            if (Singleton<WifiPvpConfromView>.Instance.IsOpened)
            {
                if (this.isConnected)
                {
                    string word = LanguageManager.GetWord("WifiPvp.ConfirmViewEnter");
                    Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.StartButton, true, true, word, delegate (GameObject go) {
                        Debug.Log("主机端按下开始按钮");
                        this.EnterPVPFinal();
                    });
                    Singleton<WifiPvpConfromView>.Instance.UpdateButtonState(com.game.module.WiFiPvP.ButtonType.ChangeButton, false, false, string.Empty, null);
                }
                else
                {
                    MessageManager.Show(LanguageManager.GetWord("WifiPvp.EnemyOffline"));
                    this.GiveUp();
                }
            }
            else
            {
                vp_Timer.In(0.1f, new vp_Timer.Callback(this.EnterPVPStepThree), null);
            }
        }

        private void UpdateMyHostName()
        {
            this.meController = AppMap.Instance.me.Controller as MeControler;
            this.DoUpdateMyFighterInfo();
            this.UpdateMyHostNameFromFighterInfo();
        }

        private void UpdateMyHostNameFromFighterInfo()
        {
            this.lastHostName = this.myHostName;
            this.myFullInfo.acc.isAvailable = !(GlobalData.isInCopy || this.isInPvp);
            object[] objArray1 = new object[] { this.myFullInfo.acc.accountName, '#', this.myFullInfo.acc.accountLevel, '#', Convert.ToByte(this.myFullInfo.acc.isAvailable).ToString(), '#', this.myFullInfo.acc.onFightGeneralId.ToString(), '#', this.myFullInfo.acc.accountFightEffect, '*' };
            this.myHostName = string.Concat(objArray1);
            foreach (PVPGeneralBrief brief in this.myFullInfo.genList)
            {
                object[] objArray2 = new object[] { this.myHostName, brief.id, '#', brief.generalTid, '#', brief.level, '#', brief.starInfo, '#', brief.job, '#', brief.name, '#', '$' };
                this.myHostName = string.Concat(objArray2);
            }
            if ((this.lastHostName != this.myHostName) && (this.ls != null))
            {
                this.ls.UpdateIpEnt(this.myHostName, 0);
            }
        }

        public void UpdateRemoteRecordWhenChange()
        {
            this.UpdateMyHostName();
        }

        private void UpdateSavedDic(TNet.List<ServerList.Entry> list)
        {
            this.cacheDic.Clear();
            IEnumerator<ServerList.Entry> enumerator = list.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    ServerList.Entry current = enumerator.Current;
                    this.cacheDic.Add(current.internalAddress, current);
                }
            }
            finally
            {
                if (enumerator == null)
                {
                }
                enumerator.Dispose();
            }
        }

        public WifiPvpConst.PVPEndState EndFlag
        {
            get
            {
                return this.endFlag;
            }
            set
            {
                this._lastEndFlag = this.endFlag;
                this.endFlag = value;
            }
        }

        private bool IsInEnding
        {
            get
            {
                return this._isInEnding;
            }
            set
            {
                this._isInEnding = value;
            }
        }

        public bool IsInitialized
        {
            get
            {
                return this.isInitialized;
            }
        }

        public bool IsInPvp
        {
            get
            {
                return this.isInPvp;
            }
        }

        public bool IsMaster
        {
            get
            {
                return this.isMaster;
            }
            set
            {
                this.isMaster = value;
            }
        }

        [CompilerGenerated]
        private sealed class <PropmtForConfirm>c__AnonStorey103
        {
            internal WifiLAN <>f__this;
            internal InviteData data;

            internal void <>m__10E()
            {
                this.<>f__this.ConfirmPVPAndConnect(this.data);
            }

            internal void <>m__10F()
            {
                this.<>f__this.DenyPVPRequest(this.data);
            }
        }
    }
}

